<?php 
include_once('database.php');
include_once('session_start.php');

$name = trim($_POST["Name"]);
$media = $_POST["Media"];
$genre = $_POST["GenreName"];
$releasedate = $_POST["Year"].'-'.$_POST["Month"].'-'.$_POST["Day"];

if($_POST["net_picture"] != ""
|| $_POST["net_picture"] != NULL){
	$picture["name"] = $_POST["net_picture"];
	$explode = explode(".", $picture["name"]);
	$extension = end($explode);
	$picture["type"] = "image/".$extension;
	$picture["size"] = 0;
}else{
	$picture = $_FILES["local_picture"];
}

foreach($_POST as $k => $v){
    $_SESSION["Material"][$k]=$v;
}

if(($name&&$media&&$genre&&$_POST["Year"]&&$_POST["Month"]&&$_POST["Day"])!=""
|| ($name&&$media&&$genre&&$_POST["Year"]&&$_POST["Month"]&&$_POST["Day"])!=NULL) {
	// Start of picture upload and checking if it's right file type and doesn't exceed max file size.
	failnetpicture:

	$allowedextensions = array("gif", "jpeg", "jpg", "png");
	$explode = explode(".", $picture["name"]);
	$extension = end($explode);

	if($picture["name"]=="" || $picture["name"]==NULL){
		// If no file was given.
		$query = $db -> prepare('INSERT INTO item (Name,MediaId,ReleaseDate) 
								 VALUES (?,?,?);');
		$query -> bind_param('sis',$name,$media,$releasedate);
		$query -> execute();
		$itemid = $query -> insert_id;
		
		$db-> query("INSERT INTO itemimage(MaterialId) VALUES(".$itemid.")");
        					 
	}else{	    
		if($_POST["net_picture"] != ""
		|| $_POST["net_picture"] != NULL){
			if(in_array($extension, $allowedextensions)){
				//NET PICTURE INSERT
				$q = $db -> prepare('INSERT INTO item (Name,MediaId,ReleaseDate) 
									 VALUES (?,?,?);');
				$q -> bind_param('sis',$name,$media,$releasedate);
				$q -> execute();
				$itemid = $q -> insert_id;
                
                $db-> query("INSERT INTO itemimage(filename, MaterialId) 
                             VALUES('".mysqli_real_escape_string($db,$picture["name"])."',".$itemid.")");
			}else{
				//LOCAL PICTURE INSERT
				$picture = $_FILES["local_picture"];
				if($picture["name"] == '' || $picture["name"] == NULL){
					$_SESSION["H7_Library_Message"]="Forkert eller for stor fil";
					header('Location:create_material.php');
					die;
				
				}
				$_POST["net_picture"] = "";
				goto failnetpicture;

			}
		}else{
			if ((($picture["type"] == "image/gif")	
			|| ($picture["type"] == "image/jpeg")
			|| ($picture["type"] == "image/jpg")
			|| ($picture["type"] == "image/png"))
			&& ($picture["size"] < $_POST["MAX_FILE_SIZE"])
			&& in_array($extension, $allowedextensions)){
				if ($picture["error"] > 0) {
					$_SESSION["H7_Library_Message"]=htmlspecialchars($picture["error"]);
					header('Location:create_material.php');
					die;
				}else{
					$stmt = $db ->prepare('INSERT INTO item (Name,MediaId,ReleaseDate)
										   VALUES (?,?,?)');
					$stmt ->bind_param('sis',$name,$media,$releasedate);
					$stmt ->execute();
					$itemid = $stmt -> insert_id;
					
                    $query = $db -> prepare("INSERT INTO itemimage (filename, mime_type, file_size, file_data, MaterialId)
                                      VALUES (?, ?, ?, ?, ?)");
                    $query ->bind_param('ssisi',$picture['name'],$picture['type'],$picture['size'],file_get_contents($picture['tmp_name']),$itemid);
                    $query ->execute();					
				}
			}else{
				$_SESSION["H7_Library_Message"]="Forkert eller for stor fil";
				header('Location:create_material.php');
				die;

			}
		}
	}
	// End of picture upload
	foreach ($genre as $value) {
		$db->query("INSERT INTO itemgenre
					 VALUES (".$itemid.",".$value.");");
	}
	// End of genres
	unset($_SESSION["Material"]);
	header('Location:index.php');

}else{
	$_SESSION["H7_Library_Message"]="Alle felter blev ikke fyldt ud";
	header('Location:create_material.php');
}
?>